package com.adu.music.parser;

import com.adu.music.util.CommonUtils;
import com.adu.music.util.EncryptUtils;
import com.adu.music.util.JsoupUtils;
import com.adu.music.util.RegexUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author duchuanchuan
 * @date 2016/12/8
 */
public class SongParser {

    private static final Logger logger = LoggerFactory.getLogger(SongParser.class);

    /**
     * 根据ID抓取歌曲信息
     * @param songId 歌曲Id
     * @return 歌曲信息
     */
    public static Map<String, Object> parseSong(String songId) {
        String url = "http://music.163.com/song?id=" + songId;
        Optional<Document> docOptional = JsoupUtils.get(url);
        Map<String, Object> song = new HashMap<>();
        docOptional.ifPresent(doc -> {
            if(StringUtils.contains(doc.html(), "网页找不到")){
                logger.info("你要查找的网页找不到,url:{}", url);
                return;
            }
            // 歌曲名称
            Elements tits = doc.select("em.f-ff2");
            if (tits.isEmpty()) {
                logger.info("抓取歌曲名称异常,url:{}", url);
                return;
            }
            String name = tits.get(0).text();

            Elements desElements = doc.getElementsByAttributeValue("class", "des s-fc4");
            if (desElements.size() < 2) {
                logger.info("抓取歌曲所属歌手异常,url:{}", url);
                return;
            }
            Elements artAnchors = desElements.get(0).getElementsByTag("a");
            // 歌手ID, 多个逗号分割
            String artistIds = "";
            // 歌手名称，多个逗号分割
            String artistNames = "";
            if (artAnchors.size() > 0) {
                for (int i = 0; i < artAnchors.size(); i++) {
                    Element artAnchor = artAnchors.get(i);
                    artistIds += StringUtils.substringAfter(artAnchor.attr("href"), "id=");
                    artistNames += artAnchor.text();
                    if (i < (artAnchors.size() - 1)) {
                        artistIds += ",";
                        artistNames += ",";
                    }
                }
            } else {
                Element span = desElements.get(0).child(0);
                artistNames = span.attr("title");
            }
            Elements albumAnchors = desElements.get(1).getElementsByTag("a");
            Element albumAnchor = albumAnchors.get(0);
            // 专辑ID
            String albumId = StringUtils.substringAfter(albumAnchor.attr("href"), "id=");
            // 专辑名称
            String albumName = albumAnchor.text();
            // 评论数量
            int comment = parseCommentNum(songId);
            song.put("id", CommonUtils.parseInt(songId));
            song.put("name", name);
            song.put("artist_id", artistIds);
            song.put("artist_name", artistNames);
            song.put("album_id", CommonUtils.parseInt(albumId));
            song.put("album_name", albumName);
            song.put("comment", comment);
        });
        return song;
    }

    /**
     * 根据歌曲ID抓取评论数量
     * @param songId 歌曲ID
     * @return 评论数量
     */
    private static int parseCommentNum(String songId) {
        String url = "http://music.163.com/weapi/v1/resource/comments/R_SO_4_" + songId + "/?csrf_token=";
        String params = "{\"rid\":\"R_SO_4_" + songId + "\",\"offset\":\"0\",\"total\":\"true\",\"limit\":\"20\",\"csrf_token\":\"\"}";
        Map<String, String> encParams = EncryptUtils.neteaseParamsEncrypt(params);
        Map<String, String> headers = new HashMap<>(1);
        headers.put("Referer", "http://music.163.com/song?id=" + songId);
        Optional<Document> docOptional = JsoupUtils.post(url, encParams, headers);
        if (docOptional.isPresent()) {
            String respContent = docOptional.get().text();
            if (StringUtils.isBlank(respContent)) {
                return 0;
            }
            String comment = RegexUtils.getMatchedString("\"total\":(\\d+?),", respContent, 1);
            return CommonUtils.parseInt(comment);
        }
        return 0;
    }
}
